/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: UserController.java</p>
 *
 * @author zz
 * @date 2024/2/4
 * @version 1.0
 * History:
 * v1.0.0 2024/2/4 Create
 */
package com.sqlweb.sqlweb.controller;

/**
 * <p>Title: UserController</p>
 * <p>Description: </p>
 *
 * @author zz
 */

import com.sqlweb.sqlweb.base.Result;
import com.sqlweb.sqlweb.base.ResultCode;
import com.sqlweb.sqlweb.entity.User;
import com.sqlweb.sqlweb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/listAll")
    public Result getAllUsers() {
        List<User> users = userService.findAll();
        return new Result(ResultCode.SUCCESS, users);
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping("/create")
    public Result createUser(@RequestBody User user) {
        userService.save(user);
        return new Result(ResultCode.SUCCESS, "创建成功");
    }

    @PutMapping("/{id}")
    public Result updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.save(user);
        return new Result(ResultCode.SUCCESS, "编辑成功");
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return new Result(ResultCode.SUCCESS, "删除成功");
    }
}

